package com.example.demonstrate.wang.annotation;

import com.google.common.util.concurrent.RateLimiter;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author along
 * @Date 2024/6/11 15:47
 */

@Aspect
@Component
public class RateLimiterAspect {

    private final RateLimiter rateLimiter;

    @Autowired
    public RateLimiterAspect(RateLimiter rateLimiter) {
        this.rateLimiter = rateLimiter;
    }

    @Around("@annotation(rateLimited)")
    public Object applyRateLimit(ProceedingJoinPoint joinPoint, RateLimited rateLimited) throws Throwable {
        if (!rateLimiter.tryAcquire(rateLimited.permits())) {
            throw new RuntimeException("Too many requests. Please try again later.");
        }
        return joinPoint.proceed();
    }
}
